package com.xiaoge.demo.web;

import com.xiaoge.demo.configs.annotation.token.PassToken;
import com.xiaoge.demo.core.Result;
import com.xiaoge.demo.core.ResultGenerator;
import com.xiaoge.demo.core.ServiceException;
import com.xiaoge.demo.dao.AddressDao;
import com.xiaoge.demo.dao.RetailListDao;
import com.xiaoge.demo.dao.UserDao;
import com.xiaoge.demo.dto.UserDto;
import com.xiaoge.demo.pojo.RetailList;
import com.xiaoge.demo.pojo.User;
import com.xiaoge.demo.utils.ValidateUtils;
import com.xiaoge.demo.vo.UserAddressVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "登陆相关")
@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    UserDao demoDao;

    @Autowired
    RetailListDao retailDao;

    @Autowired
    AddressDao mAddressDao;

    @ApiOperation("添加")
    @PostMapping("/add")
    @PassToken
    Result add(@RequestParam String name) {
        ValidateUtils.getInstance().validateData(name);
        User d = new User();
        d.setName(name);
        User save = demoDao.save(d);
        return ResultGenerator.genSuccessResult(save.getId() + ":::" + save.getName());
    }

    @ApiOperation("添加")
    @PostMapping("/add_retail")
    @PassToken
    Result addRetail(@RequestParam String name) {
        ValidateUtils.getInstance().validateData(name);
        RetailList d = new RetailList();
        d.setName(name);
        RetailList save = retailDao.save(d);
        return ResultGenerator.genSuccessResult(save.getId() + ":::" + save.getName());
    }

    @ApiOperation("获取所有")
    @PostMapping("/get")
    @PassToken
    Result get() {
        List<UserDto> all = demoDao.findPartMsgList(PageRequest.of(0, 20, new Sort(Sort.Direction.DESC, "name")));
        return ResultGenerator.genSuccessResult(all);
    }

    @PostMapping("/get_add")
    @PassToken
    Result getAdd() {
        UserAddressVo info = new UserAddressVo();
        info.setUser(demoDao.getOneById("U00000000001"));
        info.setAddress(mAddressDao.getUserAddress("U00000000001"));
        return ResultGenerator.genSuccessResult(info);
    }

    @PostMapping("/get_add2")
    @PassToken
    Result getUserAddressInfo() {
        try {
            List<Map> list = mAddressDao.getAddressAndUserInfo("U00000000001");
            return ResultGenerator.genSuccessResult(list);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
}